package bsc.war.form;


import bsc.ejb.entity.Dimension;
import bsc.ejb.entity.DimensionMember;
import bsc.ejb.entity.DimensionalCut.Type;
import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

/**
 *
 * @author memozac
 */
public class NewDimension extends AbstractController  {

     @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request,
         HttpServletResponse response) throws Exception {
        
        try {
            System.out.println("Entre aquí para editar");
            DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");
            
            Dimension dimension = request.getParameter("existingDimensionId") != null &&
                    NumberUtils.isNumber(request.getParameter("existingDimensionId")) ?
                        delegate.findDimension(Long.parseLong(request.getParameter("existingDimensionId"))) :
                        (Dimension) Factory.getBean("Dimension");
            dimension.setName(request.getParameter("existingDimensionName") != null ?
                request.getParameter("existingDimensionName") : request.getParameter("newDimensionName"));

            DimensionMember totalMember = null;

            String editMode= request.getParameter("type") != null ? request.getParameter("type") : "";

            if(editMode.equals("edit"))
                request.setAttribute("edit", Boolean.TRUE);

            if(request.getParameter("existingDimensionId")==null)
            {
                delegate.createDimension(dimension);
                totalMember = (DimensionMember)Factory.getBean("DimensionMember");
                totalMember.setName("TOTAL_"+dimension.getName());
                totalMember.setDimension(dimension);
                totalMember.setType(Type.TOTAL);
                delegate.createDimensionMember(totalMember);
            }
            else
            {
                // Actualiza DimensionMember TOTAL_NOMBRE
                delegate.updateDimension(dimension);
                totalMember = delegate.findDimensionMember(dimension).get(0);
                totalMember.setName("TOTAL_"+request.getParameter("existingDimensionName"));
                totalMember.setType(Type.TOTAL);
                delegate.updateDimensionMember(totalMember);
                // Actualiza DimensionMembers existentes
                if( request.getParameterValues("existingDimensionMember") != null && request.getParameterValues("existingDimensionMember").length > 0 )
                    for(String dimensionMemberID : request.getParameterValues("existingDimensionMember"))
                    {
                        if(!NumberUtils.isNumber(dimensionMemberID)) continue;
                        DimensionMember dimensionMember = delegate.findDimensionMember(Long.parseLong(dimensionMemberID));
                        dimensionMember.setName(request.getParameter("existingDimensionMember-"+dimensionMemberID));
                        //dimensionMember.setType(Type.STANDARD);
                        delegate.updateDimensionMember(dimensionMember);
                    }
            }

            // Crea nuevos DimensionMembers

            HashMap<String, DimensionMember> dimensionMembers = new HashMap<String, DimensionMember>();

            // CUSTOM DIMENSION MEMBERS
            if( request.getParameterValues("newDimensionMember") != null && request.getParameterValues("newDimensionMember").length > 0 )
            for(String dimensionMemberID : request.getParameterValues("newDimensionMember"))
            {
                System.out.println("String: "+dimensionMemberID+" Tamaño: "+dimensionMemberID.length());
                if(dimensionMemberID.length() < 1) continue;
                DimensionMember dimensionMember = (DimensionMember)Factory.getBean("DimensionMember");
                dimensionMember.setName(request.getParameter("newDimensionMemberName-"+dimensionMemberID));
                dimensionMember.setType(Type.STANDARD);
                if( !(dimensionMemberID.startsWith("existing:") && dimensionMemberID.indexOf("-") == dimensionMemberID.lastIndexOf("-"))  ) // El nuevo miembro no pertenece a un miembro existente
                {
                    if(dimensionMemberID.indexOf("-") == dimensionMemberID.lastIndexOf("-"))
                        dimensionMember.setDimensionMember(totalMember);
                    else
                        dimensionMember.setDimensionMember(dimensionMembers.get(
                                dimensionMemberID.startsWith("existing:") ?
                                dimensionMemberID.substring("existing:".length(),dimensionMemberID.lastIndexOf("-")) :
                                dimensionMemberID.substring(0,dimensionMemberID.lastIndexOf("-")) ));
                }
                else
                {
                    Long id = Long.parseLong(dimensionMemberID.substring("existing:".length(), dimensionMemberID.indexOf("-")));
                    dimensionMember.setDimensionMember(delegate.findDimensionMember(id));
                }
                dimensionMember.setDimension(dimension);
                delegate.createDimensionMember(dimensionMember);
                dimensionMembers.put(dimensionMemberID, dimensionMember);
            }

            delegate.updateDimension(dimension);
            
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Caught exception "+ e);
            
        }
         
         return new ModelAndView("newDimension");
    }

}
